//
//  UIScrollView+zj.swift
//  ZJSwiftKit
//
//  Created by 左潇 on 2023/6/30.
//

import Foundation


// MARK: - Methods
public extension ZJPrefix where Base: UIScrollView {
    /// 获取整个ScrollView的快照
    ///
    ///    AnySubclassOfUIScrollView().snapshot
    ///    UITableView().snapshot
    ///
    /// - Returns: 返回整个UIScrollView 的视图生成的图片
    var snapshot: UIImage? {
        // Original Source: https://gist.github.com/thestoics/1204051
        UIGraphicsBeginImageContextWithOptions(base.contentSize, false, 0)
        defer {
            UIGraphicsEndImageContext()
        }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        let previousFrame = base.frame
        base.frame = CGRect(origin: base.frame.origin, size: base.contentSize)
        base.layer.render(in: context)
        base.frame = previousFrame
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    /// 滚动视图当前可见的区域。
    var visibleRect: CGRect {
        let contentWidth = base.contentSize.width - base.contentOffset.x
        let contentHeight = base.contentSize.height - base.contentOffset.y
        return CGRect(origin: base.contentOffset,
                      size: CGSize(width: min(min(base.bounds.size.width, base.contentSize.width), contentWidth),
                                   height: min(min(base.bounds.size.height, base.contentSize.height), contentHeight)))
    }
}

